import cfg
import sys
import time

#import logging
from logging import CRITICAL,ERROR,WARNING,INFO,DEBUG,NOTSET
SPAM=5
GARBAGE=1

levels = [
('CRITICAL',50),
('ERROR',40),
('WARNING',30),
('INFO',20),
('DEBUG',10),
('SPAM',5),
('GARBAGE',1),
('NOTSET',0)
]

levelnames = {}
namelevels = {}

for name,level in levels:
	levelnames[level] = name
	namelevels[name] = level

class Logger:
	def __init__(self,name,path='',level=INFO,chain=None):
		self.name = name
		self.level = level
		self.path = path
		self.chain = chain
		self.fmt = '%(asctime)s;%(name)s;%(levelname)s;%(message)s'
		self.dfmt = '%Y-%m-%d;%H:%M:%S'

	def log(self,level,msg,*args):
		if level>=self.level:
			if self.path:
				_f = open(self.path,'a')
			else:
				_f = sys.stderr
			asctime = time.strftime(self.dfmt)
			levelname = levelnames.get(level,'LEVEL'+str(level))
			name = self.name
			try:
				message = msg % args
			except:
				message = msg + str(args)
			record = self.fmt % locals()
			_f.write(record+"\n")
			if _f<>sys.stderr:
				_f.close()
		if self.chain:
			self.chain.log(level,msg,*args)

	def critical(self,msg,*args):
		self.log(CRITICAL,msg,*args)
		
	def error(self,msg,*args):
		self.log(ERROR,msg,*args)
		
	def warning(self,msg,*args):
		self.log(WARNING,msg,*args)
		
	def info(self,msg,*args):
		self.log(INFO,msg,*args)
		
	def debug(self,msg,*args):
		self.log(DEBUG,msg,*args)
		
	def spam(self,msg,*args):
		self.log(SPAM,msg,*args)

	def garbage(self,msg,*args):
		self.log(garbage,msg,*args)

def get_job_logger(name,date,runid=1,level=INFO):
	day_logger = Logger('job.%s.%s.run%s'%(date,name,runid),cfg.get_day_log_path(date),INFO)
	job_logger = Logger('job.%s.%s.run%s'%(date,name,runid),cfg.get_job_log_path(date,name),level,chain=day_logger)
	return job_logger

def get_sch_logger(level=INFO):
	p = cfg.get_sch_log_path()
	sch_logger = Logger('sch',p,level)
	return sch_logger

if __name__=="__main__":
	#jlo=get_job_logger('test','20111204')
	#jlo.debug('to jest debug day loggera')
	#jlo.info('to jest informacja day loggera')
	lo=Logger('testowy',r'test.log')
	lo2=Logger('kolejny',r'test2.log',chain=lo)
	lo2.error('wpis replikowany')
